package com.szp.drug.component.controller;

import com.github.pagehelper.PageInfo;
import com.szp.drug.entity.DrugAdmin;
import com.szp.drug.component.service.api.DrugAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员前端控制器
 * @author SuZePing
 * @create 2021-01-09 21:03
 * @E-mail suzeping10@126.com
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class DrugAdminController {

	@Autowired
	private DrugAdminService adminService;

	/**
	 * 分页获取管理员列表(含关键词搜索)
	 * @param keyword
	 * @param pageNum
	 * @param pageSize
	 * @param map
	 * @return
	 */
	@GetMapping("/get/page.html")
	public String getPageInfo( // [defaultValue]设置默认值
			@RequestParam(value = "keyword", defaultValue = "")String keyword,
			@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "5")Integer pageSize,
			ModelMap map){

		PageInfo<DrugAdmin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);
		map.addAttribute("pageInfo",pageInfo);
		return "admin-page";
	}

	/**
	 * 删除admin
	 * @param userId
	 * @param pageNum
	 * @param keyword
	 * @return
	 */
	@GetMapping("/remove/{userId}/{pageNum}/{keyword}.html")
	public String removeAdmin(@PathVariable("userId")String userId,
							  @PathVariable("pageNum")Integer pageNum,
							  @PathVariable("keyword")String keyword){

		adminService.removeAdmin(userId);
		return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
	}

	/**
	 * 新增admin
	 * @param admin
	 * @return
	 */
	@PostMapping("/save.html")
	public String saveAdmin(DrugAdmin admin){
		log.debug("admin:{}",admin);
		adminService.saveAdmin(admin);
		return "redirect:/admin/get/page.html?pageNum=" + Integer.MAX_VALUE;
	}

	/**
	 * 修改时回显admin数据
	 * @return
	 */
	@GetMapping("/to/edit/page.html")
	public String echoAdmin(@RequestParam("adminId") String adminId, ModelMap map){
		DrugAdmin admin = adminService.getAdminById(adminId);
		map.addAttribute("selAdmin",admin);
		return "admin-edit";
	}

	/**
	 * 修改admin
	 * @param admin
	 * @param pageNum
	 * @param keyword
	 * @return
	 */
	@PostMapping("/edit.html")
	public String editAdmin(DrugAdmin admin,
							@RequestParam("pageNum") Integer pageNum,
							@RequestParam("keyword") String keyword){
		adminService.editAdmin(admin);
		return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
	}
}